//
//  RSRefreshTableView.m
//  iAccountBook
//
//  Created by 侯伟 on 2020/1/10.
//  Copyright © 2020 侯伟. All rights reserved.
//

#import "RSRefreshTableView.h"
#import <MJRefresh/MJRefresh.h>
#import <LYEmptyView/LYEmptyView.h>
#import <LYEmptyView/UIView+Empty.h>
#import "UIImage+GIFImage.h"

@interface RSRefreshTableView ()

@property(nonatomic,copy)NSString* emptyTitleStr;
@property(nonatomic,copy)NSString* emptyDetailStr;

//请求数据错误时提醒
@property(nonatomic,copy)NSString* errorTitleStr;
@property(nonatomic,copy)NSString* errorDetailStr;
@property(nonatomic,copy)NSString* errorButtonStr;



@end

@implementation RSRefreshTableView

- (LYEmptyView*)loadEmptyView{
    if(!_loadEmptyView){

        LYEmptyView* emptyView = [LYEmptyView emptyViewWithImageStr:@"common_empty_nodata" titleStr:self.emptyTitleStr detailStr:self.emptyDetailStr];
        emptyView.contentViewOffset = -100;
        
        _loadEmptyView = emptyView;
        
    }
    return _loadEmptyView;
}



- (LYEmptyView*)emptyView{
    if(!_emptyView){
        LYEmptyView* emptyView = [LYEmptyView emptyViewWithImageStr:@"common_empty_nodata" titleStr:self.emptyTitleStr detailStr:self.emptyDetailStr];
        emptyView.titleLabFont = FONT_FIT(15);
        emptyView.titleLabTextColor = COLOR_BLACK_DARK;
        emptyView.detailLabFont = FONT_FIT(12);
        emptyView.detailLabTextColor = COLOR_GRAY_BASE;
        emptyView.detailLabMargin = 10;
        emptyView.contentViewOffset = -100;
        _emptyView = emptyView;
    }
    return _emptyView;
}

- (LYEmptyView*)errorView{
    if(!_errorView){
        LYEmptyView* errorView = [LYEmptyView emptyActionViewWithImage:[UIImage imageNamed:@"common_empty_error"] titleStr:self.errorTitleStr detailStr:self.errorDetailStr btnTitleStr:self.errorButtonStr target:self action:@selector(retry)];
        errorView.titleLabFont = FONT_FIT(15);
        errorView.titleLabTextColor = COLOR_BLACK_DARK;
        errorView.detailLabFont = FONT_FIT(12);
        errorView.detailLabTextColor = COLOR_GRAY_BASE;
        errorView.actionBtnFont = FONT_FIT(14);
        errorView.actionBtnWidth = PX(192);
        errorView.actionBtnHeight = PX(40);
        errorView.actionBtnCornerRadius = PX(4.0);
        errorView.actionBtnBackGroundColor = COLOR_BACKGEOUND;
        errorView.actionBtnTitleColor = COLOR_THEME;
        errorView.detailLabMargin = 10;
        errorView.actionBtnMargin = 32;
        errorView.contentViewOffset = -100;
        _errorView = errorView;
    }
    return _errorView;
}


- (instancetype)init{
    self = [super init];
    if (self) {
        [self initProperty];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initProperty];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    self = [super initWithFrame:frame style:style];
    if (self) {
        [self initProperty];
    }
    return self;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    [self initProperty];
}

- (void)initProperty{
    self.refreshEnabled = YES;
    self.loadMoreEnabled = YES;
    self.enbaleEmptyView = YES;
    self.datas = [NSMutableArray array];
    self.pageIndex = 1;
    self.total = LINK_MAX;
    self.pageSize = 20;
    self.emptyTitleStr = @"暂无数据";
    self.emptyDetailStr = @"好像什么都没有";
    
    self.errorTitleStr = @"哎呀！出错啦～";
    self.errorDetailStr = @"请重新刷新一下页面";
    self.errorButtonStr = @"点击重试";
   
    self.tableFooterView = [UIView new];
    
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    
    if (@available(iOS 11.0, *)) {
        self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
}

#pragma mark -- setter
- (void)setRefreshEnabled:(BOOL)refreshEnabled{
    if(refreshEnabled == _refreshEnabled)
        return;
    _refreshEnabled = refreshEnabled;
    if(refreshEnabled){
        MJRefreshNormalHeader* header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            if(self.refreshDelegate && [self.refreshDelegate respondsToSelector:@selector(tableView:refreshType:)]){
                [self.refreshDelegate tableView:self refreshType:Refresh];
            }
        }];
        header.arrowView.image = [[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"arrow@2x" ofType:@"png"]] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        header.stateLabel.font = FONT(13);
        header.stateLabel.textColor = COLOR_GRAY_BASE;
        header.lastUpdatedTimeLabel.font = FONT(11);
        header.lastUpdatedTimeLabel.textColor = COLOR_GRAY_BASE;
        header.labelLeftInset = 16;
        self.mj_header = header;
        self.ly_emptyView = self.loadEmptyView;
    }else{
        self.mj_header = NULL;
        self.ly_emptyView = NULL;
    }
}

- (void)setLoadMoreEnabled:(BOOL)loadMoreEnabled{
    if(loadMoreEnabled == _loadMoreEnabled)
        return;
    _loadMoreEnabled = loadMoreEnabled;
    if(loadMoreEnabled){
        MJRefreshAutoNormalFooter* footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if(self.refreshDelegate && [self.refreshDelegate respondsToSelector:@selector(tableView:refreshType:)]){
                [self.refreshDelegate tableView:self refreshType:LoadMore];
            }
        }];

        footer.automaticallyRefresh = NO;
        footer.stateLabel.font = FONT(13);
        footer.stateLabel.textColor = COLOR_GRAY_BASE;
        self.mj_footer = footer;
        self.mj_footer.hidden = YES;
    }else{
        self.mj_footer = NULL;
    }
    
}


- (void)refreshData:(RefreshType)refreshType{
    switch (refreshType) {
        case Refresh:{
            if(_refreshEnabled){
                [self.mj_header beginRefreshing];
            }
        }
            break;
        case LoadMore:{
            if(_loadMoreEnabled)
                [self.mj_footer beginRefreshing];
        }
            break;
        default:
            break;
    }
}

- (void)updateData:(NSArray*)data refreshType:(RefreshType)refreshType isSuccess:(BOOL)isSuccess{
    switch (refreshType) {
        case Refresh:{
            if(isSuccess){
                [self.datas removeAllObjects];
                [self.datas addObjectsFromArray:data];
            }
        }
            break;
        case LoadMore:{
            if(isSuccess){
                [self.datas addObjectsFromArray:data];
            }
        }
            break;
        default:
            break;
    }
    [self endRefresh:refreshType isNoMoreData:self.datas.count >= self.total];
    
    if(self.enbaleEmptyView){
        if(isSuccess){
            self.ly_emptyView = self.emptyView;
        }else{
            self.ly_emptyView = self.errorView;
        }
    }else{
        self.ly_emptyView = NULL;
    }
}

- (void)endRefresh:(RefreshType)refreshType isNoMoreData:(BOOL)isNoMoreData{
    switch (refreshType) {
        case Refresh:{
            if([self.mj_header isRefreshing]){
                [self.mj_header endRefreshing];
            }
        }
            break;
        case LoadMore:{
            if([self.mj_footer isRefreshing]){
                [self.mj_footer endRefreshing];
            }
        }
            break;
        default:
            break;
    }
    
    if(isNoMoreData){
        [self.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.mj_footer resetNoMoreData];
    }
    
    [self reloadData];
    
    if(0 == [self mj_totalDataCount]){
        self.mj_footer.hidden = YES;
    }else{
        
        NSArray* cells = self.visibleCells;
        if(cells.count > 0){
            UITableViewCell* cell = cells.firstObject;
            
            CGFloat height = cell.frame.size.height * self.datas.count;
            if(height > self.frame.size.height){
                self.mj_footer.hidden = NO;
            }else{
                self.mj_footer.hidden = YES;
            }
        }else{
            self.mj_footer.hidden = YES;
        }
    }
}

#pragma mark  -- action
- (void)retry{
    if(self.refreshDelegate && [self.refreshDelegate respondsToSelector:@selector(tableView:refreshType:)]){
        [self.refreshDelegate tableView:self refreshType:Refresh];
    }
}

@end

